package com.xzzz.backend.blog.server.base.param;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzzz.backend.blog.server.base.param.pojo.ParamEntity;
import com.xzzz.backend.blog.server.base.param.pojo.ParamReq;
import com.xzzz.common.base.exception.XzException404;
import com.xzzz.common.base.util.PrimaryKeyUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 系统参数信息业务接口
 */
@Slf4j
@Service
@AllArgsConstructor
public class ParamService extends ServiceImpl<ParamMapper, ParamEntity> {

    /**
     * 全部列表
     */
    public List<ParamEntity> listAll(ParamReq req) {
        return baseMapper.listAll(req.to(ParamEntity.class));
    }

    /**
     * 根据ID查询
     */
    public ParamEntity selectById(Long id) {
        return Optional.ofNullable(baseMapper.selectOne(new LambdaQueryWrapper<ParamEntity>().eq(ParamEntity::getId, id))
        ).orElseThrow(() -> new XzException404("数据不存在"));
    }

    /**
     * 根据ID查询
     */
    public List<ParamEntity> selectByNames(String... names) {
        if (ArrayUtil.isEmpty(names)) {
            return new ArrayList<>();
        }
        List<ParamEntity> list = baseMapper.selectList(new LambdaQueryWrapper<ParamEntity>().in(ParamEntity::getParamName, names));
        if (list == null) {
            return new ArrayList<>();
        }
        return list;
    }

    /**
     * 新增
     *
     * @param req 主体信息
     * @return 新增条数
     */
    @Transactional(rollbackFor = Exception.class)
    public Long insert(ParamReq req) {
        ParamEntity entity = req.to(ParamEntity.class);
        entity.setId(PrimaryKeyUtil.nextId());
        baseMapper.insert(entity);
        return entity.getId();
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public Long update(ParamReq req) {
        XzException404.throwBy(req.getId() == null, "ID不得为空");
        baseMapper.updById(req.to(ParamEntity.class));
        return req.getId();
    }
}